<?php
class Mysql_dr extends Db{
	private static $ins=null;
	private $cfg=array();
	private $link=null;
	
	protected function __construct(){
		$this->need_comma=false;
		$this->addslashes=true;
		$conf=Conf::getIns();
		$this->cfg=$conf->load_config();
		$this->connect();
	}
	public function __destruct(){
		$this->close();
	}
	public static function getIns(){
        if(!(self::$ins instanceof self)) {
            self::$ins=new self();
        }
        return self::$ins;
    }
	protected function connect(){
		$config_db=$this->cfg['DB'];
		$this->link=mysql_connect($config_db['host'],$config_db['user'],$config_db['pwd']);
		if($this->link){
			$r=mysql_select_db($config_db['db'],$this->link);
			if($r){
				$this->query("set names {$config_db['charset']}");
			}else{
				exit('数据库选择错误！');
			}
		}else{
			exit('数据库连接错误！');
		}
	}
	public function exec($query,$data=array()){
		$result=$this->query($query,$data);
		$r=($result==true)?true:false;
		$this->free_result($result);
		return $r;
	}
	protected function parse_sql($sql,$data=array()){
		//$count=substr_count($sql,':');
		if(!is_array($data)) return false;
		$data=addslashes_array($data);//增加反斜线
        krsort($data);//键名逆向排序
		//if($count!=count($data)) return false;
		foreach($data as $k=>$v) $sql=str_replace(":{$k}","'{$v}'",$sql);
		return $sql;
	}
	public function query($query,$data=array()){
		$query=$this->parse_sql($query,$data);
		$this->rec_sql($query);
		$r=mysql_query($query,$this->link);
		if($msg=$this->err()){
			$pos=$_SESSION['_debug_pos_'];
			$this->_log_err($pos.$msg.$query);
			unset($_SESSION['_debug_pos_']);
		}
		return $r;
	}
	public function err(){
		return mysql_error($this->link);
	}
	//MYSQL_ASSOC, MYSQL_NUM, or MYSQL_BOTH
	public function fetch_array($result,$type){
		switch($type){
			case 'ASSOC':
				return mysql_fetch_array($result,MYSQL_ASSOC);
			break;
			case 'NUM':
				return mysql_fetch_array($result,MYSQL_NUM);
			break;
			case 'BOTH':
				return mysql_fetch_array($result,MYSQL_BOTH);
			break;
			default:
				return mysql_fetch_array($result,MYSQL_ASSOC);
			break;
		}
	}
	public function fetch_array_all($result,$type){
		$data=array();
		while($d=$this->fetch_array($result,$type)){
			$data[]=$d;
		}
		return $data;
	}
	public function fetch_row($result){
		return mysql_fetch_row($result);
	}
	public function fetch_assoc($result){
		return mysql_fetch_assoc($result);
	}
	public function free_result($result) {
		if(is_resource($result)){
			return mysql_free_result($result);
		}else{
			return true;
		}
	}
	public function insert_id() {
		return mysql_insert_id($this->link);
	}
	public function affected_rows(){
		return mysql_affected_rows($this->link);
	}
	public function close(){
		return mysql_close($this->link);
	}
//
}